﻿using System;
using System.Collections.Generic;
using NLog;

namespace dlCentral.TorrentHandlers {
    internal class TorrentHandlerManager {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private Dictionary<TorrentId, TorrentHandler> handlers;

        public TorrentHandlerManager() {
            BuildHandlerList();
        }

        public TorrentHandler this[TorrentId torrentID]
        {
            get {
                // internal handler takes priority
                if (handlers.ContainsKey(torrentID))
                    return handlers[torrentID];

                // check temporary custom handler
//                if (handlers[-1].ID == torrentID)
//                    return handlers[-1];

                // manual handler

                return null;
            }
        }

        public TorrentHandler this[TorrentHandlerType type] {
            get {
                foreach (TorrentHandler h in handlers.Values) {
                    if (h.Type == type && h.Available) {
                        return h;
                    }
                }
                return null;
            }
        }



        private void BuildHandlerList() {
            logger.Info("Checking for supported torrents...");
            handlers = new Dictionary<TorrentId, TorrentHandler>();

            // load all supported torrent handlers into our dictionary
            foreach (Type t in this.GetType().Assembly.GetTypes())
                if (t.BaseType == typeof(TorrentHandler)) {
                    TorrentHandler newHandler = (TorrentHandler)t.GetConstructor(new Type[] { }).Invoke(null);
                    handlers[newHandler.ID] = newHandler;
                }

            // log all the active plugin handlers
            foreach (TorrentHandler h in handlers.Values) {
                if (h.Available) logger.Info("Enabled torrent: {0}", h.TorrentName);
            }

            // log all the inactive plugin handlers
            foreach (TorrentHandler h in handlers.Values)
                if (!h.Available) logger.Info("Unavailable or Outdated torrent {0}", h.TorrentName);
        }
    }
}
